{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a517affc-fdef-4627-b1f5-5c4754f44c14",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import numpy as np\n",
    "\n",
    "in_path = '/home/ljw22/workspace/qwen/MUSER-main/cases_pool.json'\n",
    "\n",
    "in_file = open(in_path, 'r', encoding='utf-8')\n",
    "cases_pool = json.load(in_file)\n",
    "\n",
    "# 训练集和数据集合并，因为不需要进行训练，全部进行测试\n",
    "train_test_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/train_test.json'\n",
    "train_test_file = open(train_test_path, 'r')\n",
    "train_test = json.load(train_test_file)\n",
    "test_querys = train_test['train'] + train_test['test']  #\n",
    "\n",
    "\n",
    "qc_pairs_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/cands_by_query.json'\n",
    "qc_pairs_file = open(qc_pairs_path, 'r')\n",
    "qc_pairs = json.load(qc_pairs_file)\n",
    "\n",
    "feature_path = \"/home/ljw22/workspace/qwen/MUSER-main/data/features/14B_feature.json\"\n",
    "\n",
    "with open(feature_path) as fin:\n",
    "    feature = json.load(fin)\n",
    "\n",
    "docid_list = list(feature.keys())\n",
    "\n",
    "docid_id_dict = {}\n",
    "\n",
    "for id, docid in enumerate(docid_list):\n",
    "    docid_id_dict[docid] = id\n",
    "\n",
    "\n",
    "feature_matric = []\n",
    "for doc in docid_list:\n",
    "    feature_matric.append(feature[doc])  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8b036d94-2f75-4137-9d91-abca251b5c63",
   "metadata": {},
   "outputs": [],
   "source": [
    "docid_id_dict = {}\n",
    "for i, docid in enumerate(docid_list):\n",
    "    docid_id_dict[docid] = i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d062d48a-8c61-41c4-8bd7-9122ae94db1c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "计算余弦相似度\n",
      "(4024, 4024)\n"
     ]
    }
   ],
   "source": [
    "A = np.array(feature_matric)\n",
    "\n",
    "print(\"计算余弦相似度\")\n",
    "# 计算每一行的 L2 范数（每个特征的长度）\n",
    "norms = np.linalg.norm(A, axis=1, keepdims=True)\n",
    "\n",
    "# 计算余弦相似度矩阵\n",
    "norms[norms == 0] = 1  # 可以把零范数的行设为1，防止除以0\n",
    "\n",
    "# 计算余弦相似度矩阵\n",
    "similarity_matrix = np.dot(A, A.T) / (norms * norms.T)\n",
    "\n",
    "print(similarity_matrix.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "739efd0e-e442-4e6e-83bc-fea69b68847f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 所有候选分词之后的结果，用于进行相似度计算\n",
    "corpus_path = '/home/ljw22/workspace/qwen/MUSER-main/data/cases/corpus.json'\n",
    "corpus_file = open(corpus_path, 'r', encoding='utf-8')\n",
    "corpus = json.load(corpus_file)\n",
    "\n",
    "# 停词集合\n",
    "stopword_path = '/home/ljw22/workspace/qwen/MUSER-main/data/utils/stopword.txt'\n",
    "stopword_file = open(stopword_path, 'r', encoding='utf-8')\n",
    "lines = stopword_file.readlines()\n",
    "stopwords = [i.strip() for i in lines]\n",
    "stopwords.extend(['.','（','）','-', '', '【', '】'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c63032e8-c97d-408d-ac0a-bbac5166917f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import jieba\n",
    "from tqdm import tqdm\n",
    "from gensim.summarization import bm25"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ec4b659b-b838-42f8-a605-fcdc7a165cf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "bm25Model = bm25.BM25(corpus)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "296044a4-ba93-4914-84b7-1d54a093910b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.5\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [01:17<00:00,  1.29it/s]\n"
     ]
    }
   ],
   "source": [
    "bm25_top100 = {}\n",
    "alpha_list = [0.5]\n",
    "for alpha in alpha_list:\n",
    "    print(alpha)\n",
    "    for qid in tqdm(test_querys):\n",
    "        array_idx = docid_id_dict[qid]\n",
    "        sim_scores = []\n",
    "        query_text = ''\n",
    "        for part in ['本院查明']:\n",
    "            for sent in cases_pool[qid]['content'][part]:\n",
    "                query_text += sent\n",
    "        query_jieba = jieba.cut(query_text, cut_all=False)\n",
    "        query_tmp = ' '.join(query_jieba).split()\n",
    "        query_cutted = [w for w in query_tmp if w not in stopwords]\n",
    "        sim_ndarray = np.array(bm25Model.get_scores(query_cutted))\n",
    "        sim = (sim_ndarray / sim_ndarray.sum()).tolist()\n",
    "        # print(sim)\n",
    "        # print(len(sim))\n",
    "        # break\n",
    "        for idx, score in zip(cases_pool.keys(), sim):\n",
    "            cand_idx = docid_id_dict[idx]\n",
    "            i = int(idx)\n",
    "            if qid == i or i not in qc_pairs[qid]:\n",
    "            # if int(qid) == i:\n",
    "                continue\n",
    "            mscore = alpha * score + (1 - alpha) * similarity_matrix[array_idx][cand_idx]\n",
    "            sim_scores.append((idx, mscore))\n",
    "        # assert len(sim_scores) == 100\n",
    "        sim_scores.sort(key=lambda x:x[1], reverse=True)\n",
    "        # print(sim_scores)\n",
    "        cnt = 0\n",
    "        bm25_top100[qid] = []\n",
    "        for idx, score in sim_scores:\n",
    "            if cnt >= 100:\n",
    "                break\n",
    "            bm25_top100[qid].append(idx)\n",
    "            cnt += 1\n",
    "        assert len(bm25_top100[qid]) == 100\n",
    "    \n",
    "    out_path = f'/home/ljw22/workspace/qwen/MUSER-main/data/my_predictions/bm25_pre/alpha-{alpha}.json'\n",
    "    out_file = open(out_path, 'w')\n",
    "    json.dump(bm25_top100, out_file)\n",
    "    out_file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "585a2312-1c73-4e95-9a42-551e054573c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.5\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|                                                                                                                                                                                                               | 0/4 [00:00<?, ?it/s]\n"
     ]
    },
    {
     "ename": "KeyError",
     "evalue": "'1'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[41], line 23\u001b[0m\n\u001b[1;32m     21\u001b[0m cand_idx \u001b[38;5;241m=\u001b[39m docid_id_dict[idx]\n\u001b[1;32m     22\u001b[0m i \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mint\u001b[39m(idx)\n\u001b[0;32m---> 23\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m qid \u001b[38;5;241m==\u001b[39m i \u001b[38;5;129;01mor\u001b[39;00m i \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m \u001b[43mqc_pairs\u001b[49m\u001b[43m[\u001b[49m\u001b[43mqid\u001b[49m\u001b[43m]\u001b[49m:\n\u001b[1;32m     24\u001b[0m \u001b[38;5;66;03m# if int(qid) == i:\u001b[39;00m\n\u001b[1;32m     25\u001b[0m     \u001b[38;5;28;01mcontinue\u001b[39;00m\n\u001b[1;32m     26\u001b[0m mscore \u001b[38;5;241m=\u001b[39m alpha \u001b[38;5;241m*\u001b[39m score \u001b[38;5;241m+\u001b[39m (\u001b[38;5;241m1\u001b[39m \u001b[38;5;241m-\u001b[39m alpha) \u001b[38;5;241m*\u001b[39m similarity_matrix[array_idx][cand_idx]\n",
      "\u001b[0;31mKeyError\u001b[0m: '1'"
     ]
    }
   ],
   "source": [
    "bm25_top100 = {}\n",
    "alpha_list = [0.5]\n",
    "for alpha in alpha_list:\n",
    "    print(alpha)\n",
    "    for qid in ['1410']:\n",
    "        array_idx = docid_id_dict[qid]\n",
    "        sim_scores = []\n",
    "        query_text = ''\n",
    "        for part in ['本院查明']:\n",
    "            for sent in cases_pool[qid]['content'][part]:\n",
    "                query_text += sent\n",
    "        query_jieba = jieba.cut(query_text, cut_all=False)\n",
    "        query_tmp = ' '.join(query_jieba).split()\n",
    "        query_cutted = [w for w in query_tmp if w not in stopwords]\n",
    "        sim_ndarray = np.array(bm25Model.get_scores(query_cutted))\n",
    "        sim = (sim_ndarray / sim_ndarray.sum()).tolist()\n",
    "        # print(sim)\n",
    "        # print(len(sim))\n",
    "        # break\n",
    "        for idx, score in zip(cases_pool.keys(), sim):\n",
    "            cand_idx = docid_id_dict[idx]\n",
    "            i = int(idx)\n",
    "            if qid == i or i not in qc_pairs[qid]:\n",
    "            # if int(qid) == i:\n",
    "                continue\n",
    "            mscore = alpha * score + (1 - alpha) * similarity_matrix[array_idx][cand_idx]\n",
    "            sim_scores.append((idx, mscore))\n",
    "        # assert len(sim_scores) == 100\n",
    "        sim_scores.sort(key=lambda x:x[1], reverse=True)\n",
    "        # print(sim_scores)\n",
    "        cnt = 0\n",
    "        bm25_top100[qid] = []\n",
    "        for idx, score in sim_scores:\n",
    "            if cnt >= 100:\n",
    "                break\n",
    "            bm25_top100[qid].append(idx)\n",
    "            cnt += 1\n",
    "        assert len(bm25_top100[qid]) == 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "bb49ab4c-4a97-434d-921c-014d42e2b32d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['1410',\n",
       " '2042',\n",
       " '5129',\n",
       " '3675',\n",
       " '4809',\n",
       " '3031',\n",
       " '5596',\n",
       " '2684',\n",
       " '1000',\n",
       " '3711',\n",
       " '3281',\n",
       " '5089',\n",
       " '3368',\n",
       " '5953',\n",
       " '901',\n",
       " '5888',\n",
       " '4666',\n",
       " '5389',\n",
       " '5141',\n",
       " '1742',\n",
       " '1092',\n",
       " '305',\n",
       " '6295',\n",
       " '91',\n",
       " '4181',\n",
       " '6782',\n",
       " '1271',\n",
       " '3710',\n",
       " '431',\n",
       " '3098',\n",
       " '6090',\n",
       " '5087',\n",
       " '6057',\n",
       " '5374',\n",
       " '2628',\n",
       " '2747',\n",
       " '3883',\n",
       " '6306',\n",
       " '4067',\n",
       " '2902',\n",
       " '1937',\n",
       " '2700',\n",
       " '2398',\n",
       " '2837',\n",
       " '2273',\n",
       " '323',\n",
       " '1011',\n",
       " '1317',\n",
       " '2038',\n",
       " '270',\n",
       " '4123',\n",
       " '1279',\n",
       " '1419',\n",
       " '2696',\n",
       " '3077',\n",
       " '4399',\n",
       " '4858',\n",
       " '2952',\n",
       " '546',\n",
       " '104',\n",
       " '4329',\n",
       " '3907',\n",
       " '949',\n",
       " '952',\n",
       " '2793',\n",
       " '2722',\n",
       " '1773',\n",
       " '3994',\n",
       " '4741',\n",
       " '2127',\n",
       " '460',\n",
       " '1649',\n",
       " '5203',\n",
       " '645',\n",
       " '4984',\n",
       " '2186',\n",
       " '4179',\n",
       " '5263',\n",
       " '3565',\n",
       " '4272',\n",
       " '1496',\n",
       " '2659',\n",
       " '6',\n",
       " '3402',\n",
       " '2193',\n",
       " '4495',\n",
       " '1701',\n",
       " '2197',\n",
       " '3367',\n",
       " '956',\n",
       " '2701',\n",
       " '2106',\n",
       " '284',\n",
       " '981',\n",
       " '5436',\n",
       " '2379',\n",
       " '4029',\n",
       " '1272',\n",
       " '841',\n",
       " '2704']"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_querys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "c1aed2c7-6d22-4b77-a747-d9b0dc85ef3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "sim.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "dc2b9c02-eb46-4a7f-85d5-1dc60cecdfc9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[197.19532479989724,\n",
       " 204.08812063735672,\n",
       " 204.8128738083495,\n",
       " 208.78694544024916,\n",
       " 218.02733321407402,\n",
       " 234.74783833153703,\n",
       " 240.3537032333091,\n",
       " 243.07522597263247,\n",
       " 244.78319454502895,\n",
       " 246.01969474036764]"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim[:10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1d8328a-62a4-4482-a78e-c5b1a96937e5",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
